/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tr.com.oyunus.server.impl;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.*;
import org.jboss.netty.handler.codec.http.*;
import org.jboss.netty.util.CharsetUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tr.com.oyunus.server.command.router.CommandRouter;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.*;
import static org.jboss.netty.handler.codec.http.HttpHeaders.getHost;
import static org.jboss.netty.handler.codec.http.HttpHeaders.isKeepAlive;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.OK;
import static org.jboss.netty.handler.codec.http.HttpVersion.HTTP_1_1;

/**
 * This class handles all incoming requests.
 *
 * @author ginnun
 */
@Component(value = "simpleOyunusServerRequestHandler")
public class SimpleOyunusServerRequestHandler extends SimpleChannelUpstreamHandler {

 @Autowired
 private CommandRouter  commandRouter;

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        if (e.getMessage() instanceof HttpRequest) {

            commandRouter.routeCommand(e);
        }else if (e.getMessage() instanceof String)  {
            e.getChannel().write(e.getMessage());
            e.getChannel().close();
        }
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
            throws Exception {
        e.getCause().printStackTrace();
        if (e.getChannel().isWritable() )
            e.getCause().getMessage();
        e.getChannel().close();
    }
}
